package com.qk.web.filter;

import cn.hutool.core.util.StrUtil;
import com.qk.util.JWTUtils;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Map;

/**
 * @Author: zhangchuang
 * @Date: 2025/10/11 14:24
 * @Description: 登录过滤器
 */
@Slf4j
//@WebFilter(urlPatterns = "/*")
@SuppressWarnings("all")
public class LoginFilter implements Filter {

    private static final String TOKEN_HEADER_NAME = "token";
    private static final String LOGIN_URI = "/login";

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        if (StrUtil.equals(request.getRequestURI(), LOGIN_URI)) {
            log.info("---登录请求，放行---");
            filterChain.doFilter(request, response);
            return;
        }
        String token = request.getHeader(TOKEN_HEADER_NAME);
        if (StrUtil.isEmpty(token)) {
            log.info("---请求没有token，拒绝访问---");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        try {
            Map<String, Object> claims = JWTUtils.parseToken(token);
            log.info("----用户id：{}，用户username：{}----", claims.get(JWTUtils.KEY_ID), claims.get(JWTUtils.KEY_USERNAME));
        } catch (Exception e) {
            log.info("---解析token失败，拒绝访问---");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        log.info("---token正确，请求通过---");
        filterChain.doFilter(request, response);
    }
}
